package com.ews.onlineexchange.rest;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.app.FullTextEntity;
import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.service.NewFtService;
import com.ews.onlineexchange.util.RestParamUtil;
import com.fasterxml.jackson.core.JsonProcessingException;

import net.sf.json.JSONObject;

@Path(value = "/fullText")
@Transactional
public class FullTextSearchRest {
	@Inject
	NewFtService newFtService;
	
	@GET
	@Path("/getFullTextResultList/{pageNumber}/{pageSize}/{searchString}")
	@Produces("application/json")
	@Context
	public JSONObject getFullTextResultList(@PathParam("pageNumber") int pageNumber,@PathParam("pageSize")int pageSize,@PathParam("searchString") String searchString) throws JsonProcessingException {
		List<FullTextEntity> resultList = new ArrayList<>();
		JSONObject jsonnObject = new JSONObject();
		 searchString = RestParamUtil.getParamValue(searchString);
	    if(StringUtils.isBlank(searchString)) {
	    	jsonnObject.put("totalcount", 0);
	        jsonnObject.put("resultList", new ArrayList<>());
	        return jsonnObject;
	    }
		newFtService.refresh();
		newFtService.setFirstResult((pageNumber-1) * pageSize);
		newFtService.setMaxResults(pageSize);
		newFtService.setSearchString(RestParamUtil.getParamValue(searchString));
		 Long totalcount = newFtService.getResultCount();
		
        
		List<DataEntity> newFtResultList = newFtService.getResultList();
		for (DataEntity dataEntity : newFtResultList) {
			FullTextEntity entity = new FullTextEntity();
			entity.setClassName(dataEntity.getClassName());
			entity.setContent(dataEntity.getHighLightContent());
			entity.setCredateDate(dataEntity.getCreateDate());
			entity.setId(dataEntity.getId());
			entity.setTitle(dataEntity.getHighLightTitle());
			resultList.add(entity);
		}
		jsonnObject.put("totalcount", totalcount);
        jsonnObject.put("resultList", resultList);
		return jsonnObject;
		
	}
	
	
}
